﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cards;

namespace PokerStatisticsCalculator
{
    public static class PermutationsCalculator
    {
        public static IEnumerable<Card[]> GetAllPossiblePermutationsWithoutOrder(Card[] cards, int numberOfCards)
        {
            int[] indices = Enumerable.Range(0, cards.Length).ToArray();

            foreach (int[] subset in GetSubset(indices, numberOfCards).Distinct(ArrayEqualityComparer.Instance))
            {
                yield return GetCardSubsut(cards, subset);
            }
        }

        private static IEnumerable<int[]> GetSubset(int[] set, int subsetSize)
        {
            if (subsetSize == set.Length)
            {
                yield return set;
            }
            else
            {
                for (int i = 0; i < set.Length; i++)
                {
                    int[] subset = new int[set.Length - 1];
                    Array.ConstrainedCopy(set, 0, subset, 0, i);
                    Array.ConstrainedCopy(set, i + 1, subset, i, set.Length - i - 1);

                    foreach (var subSubset in GetSubset(subset, subsetSize))
                    {
                        yield return subSubset;
                    }
                }
            }
        }

        private static Card[] GetCardSubsut(Card[] cards, int[] indices)
        {
            Card[] subset = new Card[indices.Length];
            for (int i = 0; i < indices.Length; i++)
            {
                subset[i] = cards[indices[i]];
            }
            return subset;
        }
    }
}